package com.tarena.lbs.basic.web.service.impl;


import com.tarena.lbs.basic.web.repository.AreaRepository;
import com.tarena.lbs.basic.web.service.IAreaService;
import com.tarena.lbs.pojo.basic.bo.AreaBO;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

@Service
@Slf4j
public class AreaServiceImpl implements IAreaService {

    @Resource
    private AreaRepository areaRepository;

    /**
     * 功能描述: 根据上级数据获取下级数据
     *
     * @param parentId
     */
    @Override
    public List<AreaBO> findByParentId(Long parentId) {
        return areaRepository.findByParentId(parentId);
    }

    /**
     * 功能描述: 查询全部数据组成的省市区三级树
     */
    @Override
    public List<AreaBO> queryAreaData() {
        //获取全部区域数据
        List<AreaBO> result = new ArrayList<>();
        Map<Long,List<AreaBO>> allAreaMap = areaRepository.queryAreaData();
        //获取一级分类
        List<AreaBO> firstAreaList = allAreaMap.get(0L);
        for (AreaBO areaVo : firstAreaList) {
            result.add(areaVo);
            //获取二级分类
            List<AreaBO> secondAreaList = allAreaMap.get(areaVo.getId());
            if (CollectionUtils.isEmpty(secondAreaList)) {
                continue;
            }
            areaVo.setChildren(secondAreaList);
            //获取三级分类
            for (AreaBO secondArea : secondAreaList) {
                List<AreaBO> thirdAreaList = allAreaMap.get(secondArea.getId());
                secondArea.setChildren(thirdAreaList);
            }
        }
        return result;
    }

    /**
     * 功能描述: 根据areaid获取省市区全名
     *
     * @param areaId
     */
    @Override
    public String findByAreaId(Long areaId) {
        String address = "";
        AreaBO areaBO = areaRepository.findById(areaId);
        if (areaBO != null && areaBO.getParentId() !=null) {
            address = areaBO.getName();
            AreaBO cityBO = areaRepository.findById(areaBO.getParentId());
            if (cityBO!= null && cityBO.getParentId() !=null) {
                address = cityBO.getName() + address;
                AreaBO provinceBO = areaRepository.findById(cityBO.getParentId());
                address = provinceBO.getName() + address;
            }
        }
        return address;
    }

    /**
     * 功能描述: 查询一级省区域
     */
    @Override
    public List<AreaBO> queryProvinceList() {
        return areaRepository.queryProvinceList();
    }
}
